package com.cskt.common.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.cskt.common.constants.Constants;

import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Date;

/**
 * 阿里云OSS工具类
 *
 * @author admin
 * @date 2023/04/16 17:47
 **/

public class AliyunOssUtil {


    private static final String ENDPOINT = "https://oss-cn-hangzhou.aliyuncs.com";
    private static final String ACCESS_KEY_ID = "LTAI5tHZyQEu3hmkrzGKy1do";
    private static final String ACCESS_KEY_SECRET = "oqusanoJA8N8kWKO4vPqNCqvrI1fl6";
    private static final String BUCKET_NAME = "pet-obj";

    /**
     * 根据对象名生成软链接
     *
     * @param objectName
     * @return
     */
    public static String getSymlink(String objectName) {
        OSS client = createClient();
        //url过期时间
        Date expireDate = Date.from(
                LocalDateTime.now()
                        .plus(Constants.Time.ALI_OSS_REDIS_PATH_TIME, ChronoUnit.SECONDS)
                        .atZone(ZoneId.systemDefault())
                        .toInstant()
        );
        //生成签名的url
        return client.generatePresignedUrl(BUCKET_NAME, objectName, expireDate).toString();
    }

    /**
     * 上传文件
     * @param content 文件名，包含路径
     * @param inputStream 文件流
     * @return 带签名的文件路径
     */
    public static String uploadFile(String content, InputStream inputStream) {
        OSS client = createClient();
        //1、先判断当前要上传的bucketName是否存在
        if (!client.doesBucketExist(BUCKET_NAME)) {
            client.createBucket(BUCKET_NAME);
        }
        //2、上传文件
        client.putObject(BUCKET_NAME, content, inputStream);
        //处理文件路径
        return getSymlink(content);
    }

    /**
     * 初始化client
     *
     * @return
     */
    private static OSS createClient() {
        OSS client = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        return client;
    }

}
